package com.weme.fecebook

import android.app.Activity
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import com.facebook.*
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.facebook.share.Sharer
import com.facebook.share.model.ShareLinkContent
import com.facebook.share.widget.ShareDialog


object FaceBookHelper {

    var callbackManager: CallbackManager? = null

    //登录
    fun login(ctx: AppCompatActivity, success: (LoginResult) -> Unit, logicerror: (FacebookException) -> Unit, cancel: () -> Unit) {
        if (callbackManager == null) {
            callbackManager = CallbackManager.Factory.create()
        }
        callbackManager?.also {
            LoginManager.getInstance().logInWithReadPermissions(ctx, listOf("public_profile"))
            LoginManager.getInstance().registerCallback(it, object : FacebookCallback<LoginResult> {
                override fun onCancel() {
                    cancel.invoke()
                }

                override fun onError(error: FacebookException) {
                    error.run { logicerror.invoke(this) }
                }

                override fun onSuccess(result: LoginResult) {
                    result.run { success.invoke(this) }
                }
            })
        }
    }

    //分享url
    fun shareUrl(ctx: Activity, url: String, listener: FacebookShareListener) {
        val content: ShareLinkContent = ShareLinkContent.Builder()
            .setContentUrl(Uri.parse(url))
            .build()
        val dialog = ShareDialog(ctx)
        dialog.registerCallback(CallbackManager.Factory.create(), object : FacebookCallback<Sharer.Result>{
            override fun onCancel() {
                listener.onFail()
            }

            override fun onError(error: FacebookException) {
                listener.onFail()
            }

            override fun onSuccess(result: Sharer.Result) {
                listener.onSuccess()
            }

        })
        dialog.show(content)
    }

    fun logOut() {
        LoginManager.getInstance().logOut()
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        callbackManager?.onActivityResult(requestCode, resultCode, data)
    }

    fun onDestroy() {
        callbackManager = null
    }

    interface FacebookShareListener{
        fun onSuccess()
        fun onFail()
    }
}